<!DOCTYPE html>

<html lang="en">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>Common Modules Source: control/LayerSwitcher.js</title>

	<!--[if lt IE 9]>
	<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->
	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.simplex.css">

</head>

<body>

<div class="navbar navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
	<div class="navbar-header">
		<a class="navbar-brand" href="index.html">Common Modules</a>
		<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation">
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
        </button>
	</div>
	<div class="navbar-collapse collapse" id="topNavigation">
		<ul class="nav navbar-nav">
			
			<li class="dropdown">
				<a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a>
				<ul class="dropdown-menu ">
					<li><a href="Base.html">Base</a></li><li><a href="Event.html">Event</a></li><li><a href="Html.html">Html</a></li><li><a href="Internal.html">Internal</a></li><li><a href="ol.Overlay.Popup.html">ol.Overlay.Popup</a></li>
				</ul>
			</li>
			
			<li class="dropdown">
				<a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b class="caret"></b></a>
				<ul class="dropdown-menu ">
					<li><a href="global.html#addClass">addClass</a></li><li><a href="global.html#addListener">addListener</a></li><li><a href="global.html#arrayRemove">arrayRemove</a></li><li><a href="global.html#clear">clear</a></li><li><a href="global.html#create">create</a></li><li><a href="global.html#createHidden">createHidden</a></li><li><a href="global.html#empty">empty</a></li><li><a href="global.html#EventType">EventType</a></li><li><a href="global.html#findListener">findListener</a></li><li><a href="global.html#firstUpperToCase">firstUpperToCase</a></li><li><a href="global.html#get">get</a></li><li><a href="global.html#getChildByTagName">getChildByTagName</a></li><li><a href="global.html#getClass">getClass</a></li><li><a href="global.html#getDomEventKey">getDomEventKey</a></li><li><a href="global.html#getElementsByClassName">getElementsByClassName</a></li><li><a href="global.html#getListeners">getListeners</a></li><li><a href="global.html#getrandom">getrandom</a></li><li><a href="global.html#getStyle">getStyle</a></li><li><a href="global.html#getuuid">getuuid</a></li><li><a href="global.html#hasClass">hasClass</a></li><li><a href="global.html#isObject">isObject</a></li><li><a href="global.html#isString">isString</a></li><li><a href="global.html#layerConfigDefautls">layerConfigDefautls</a></li><li><a href="global.html#listen">listen</a></li><li><a href="global.html#listenOnce">listenOnce</a></li><li><a href="global.html#logo">logo</a></li><li><a href="global.html#OL_Style_Type">OL_Style_Type</a></li><li><a href="global.html#remove">remove</a></li><li><a href="global.html#removeClass">removeClass</a></li><li><a href="global.html#removeListener">removeListener</a></li><li><a href="global.html#removeListeners">removeListeners</a></li><li><a href="global.html#setClass">setClass</a></li><li><a href="global.html#splitWords">splitWords</a></li><li><a href="global.html#stamp">stamp</a></li><li><a href="global.html#toBack">toBack</a></li><li><a href="global.html#toFront">toFront</a></li><li><a href="global.html#trim">trim</a></li><li><a href="global.html#unListen">unListen</a></li><li><a href="global.html#unlistenAll">unlistenAll</a></li><li><a href="global.html#unListenByKey">unListenByKey</a></li><li><a href="global.html#upperFirstChart">upperFirstChart</a></li>
				</ul>
			</li>
			
		</ul>
        
            <div class="col-sm-3 col-md-3">
                <form class="navbar-form" role="search">
                    <div class="input-group">
                        <input type="text" class="form-control" placeholder="Search" name="q" id="search-input">
                        <div class="input-group-btn">
                            <button class="btn btn-default" id="search-submit"><i class="glyphicon glyphicon-search"></i></button>
                        </div>
                    </div>
                </form>
            </div>
        
	</div>

</div>
</div>


<div class="container" id="toc-content">
<div class="row">

	
	<div class="col-md-12">
	
		<div id="main">
			

		<h1 class="page-title">Source: control/LayerSwitcher.js</h1>
    
<section>
    <article>
        <pre
            class="sunlight-highlight-javascript linenums">/**
 * @ 图层切换功能控件
 */
import { ol } from '../constants'
import '../asset/scss/layerSwitcher.scss'
import {BASE_CLASS_NAME} from '../constants'
import * as htmlUtils from '../utils/domUtils'
import * as Events from '../event/Events'
import olLayerLayerUtils from '../utils/layerUtils'
import mixin from '../utils/mixinfn'
ol.control.LayerSwitcher = function (params = {}) {
  this.options = params

  /**
   * className
   * @type {string}
   */
  this.className_ = (this.options.className !== undefined ? this.options.className : 'gmap-layer-switcher')

  /**
   * width
   * @type {number}
   */
  this.options['itemWidth'] = (this.options['itemWidth'] === 'number' ? this.options['itemWidth'] : 86)

  /**
   * 底图集合
   * @type {Array}
   * @private
   */
  this.baseLayers_ = []

  /**
   * 标注图层
   * @type {Array}
   * @private
   */
  this.labelLayers_ = []

  /**
   * 用于标识底图的关键字
   * @type {string}
   */
  this.baseLayerKey = this.options['baseLayerKey'] ? this.options['baseLayerKey'] : 'isBaseLayer'

  /**
   * 用于标识当前底图的关键字
   * @type {string}
   */
  this.isDefaultKey = this.options['isDefaultKey'] ? this.options['isDefaultKey'] : 'isDefault'

  /**
   * 关联图层关键字
   * @type {string}
   */
  this.labelAliasKey = this.options['labelAlias'] ? this.options['labelAlias'] : 'layerName'

  /**
   * 标准labelLayer关键字
   * @type {string}
   */
  this.labelLayerKey = this.options['labelLayerKey'] ? this.options['labelLayerKey'] : 'isLabelLayer'

  /**
   * 是否已经默认执行选中操作
   * @type {boolean}
   * @private
   */
  this.isActionSelected_ = false

  /**
   * 是否每次操作之前强制更新图层，这在底图可能发生变化时比较有用。
   */
  this.forcedUpdate = this.options['forcedUpdate']

  /**
   * height
   * @type {number}
   */
  this.options['itemHeight'] = (typeof this.options['itemHeight'] === 'number' ? this.options['itemHeight'] : 60)

  /**
   * 图层关键字
   * @type {string}
   */
  this.options['key'] = (this.options['key'] ? this.options['key'] : 'layerName')
  if (this.labelLayerKey === this.baseLayerKey) {
    throw new Error('标注图层关键字不能和底图相同！')
  }

  /**
   * @private
   * @type {Element}
   */
  this.element_ = htmlUtils.create('div', (this.className_ + ' ' + BASE_CLASS_NAME.CLASS_UNSELECTABLE))
  Events.listen(this.element_, 'mouseover', this.contentMouseOver_, this)
  Events.listen(this.element_, 'mouseout', this.contentMouseOut_, this)

  /**
   * @private
   * @type {Element}
   */
  this.innerElement_ = htmlUtils.create('ul', this.className_ + '-ul-inner', this.element_, this.className_ + '-ul-inner')

  if (this.options['layers'] &amp;&amp; Array.isArray(this.options['layers']) &amp;&amp; this.options['layers'].length > 0) {
    this.initDomInternal(this.options['layers'], this.className_, this.options['key'])
  } else {
    this.element_.style.display = 'none'
  }
  ol.control.Control.call(this, {
    element: this.element_,
    target: this.options['target']
  })
}

ol.inherits(ol.control.LayerSwitcher, ol.control.Control)
mixin(ol.control.LayerSwitcher, olLayerLayerUtils)

/**
 * 初始化dom
 * @param layers
 * @param className
 * @param key
 */
ol.control.LayerSwitcher.prototype.initDomInternal = function (layers, className, key) {
  let width = this.options['itemWidth']
  let height = this.options['itemHeight']
  let length = layers.length
  this.innerElement_.style.width = width + (length - 1) * 10 + 'px'
  this.innerElement_.style.height = height + 'px'
  layers.forEach((item, index) => {
    if (item &amp;&amp; item[key]) {
      let li_ = htmlUtils.create('li', className + '-li-inner', this.innerElement_, className + '-li' + index + '-inner')
      li_.style.background = 'url(' + item['icon'] + ') 0px 0px no-repeat'
      li_.style.width = width + 'px'
      li_.style.height = height + 'px'
      li_.style.zIndex = index + 1
      li_.style.right = '0px'
      li_.style.marginRight = (length - 1 - index) * 10 + 'px'
      li_.setAttribute('data-name', item[key])
      Events.listen(li_, 'click', this.handleClick_, this)
      if (item['name']) {
        let name_ = htmlUtils.create('span', 'layer-name', li_)
        name_.setAttribute('data-name', item[key])
        name_.innerHTML = item['name']
      }
      if (!this.isActionSelected_) {
        if (item[this.isDefaultKey]) {
          htmlUtils.addClass(li_, 'selected-item')
          this.isActionSelected_ = true
        }
      }
      if (!this.isActionSelected_ &amp;&amp; (index === length - 1)) {
        htmlUtils.addClass(li_, 'selected-item')
        this.isActionSelected_ = true
      }
    }
  })
}

/**
 * 鼠标移入
 * @param event
 * @private
 */
ol.control.LayerSwitcher.prototype.contentMouseOver_ = function (event) {
  let length = this.options['layers'].length
  if (length > 0) {
    for (let i = 0; i &lt; length - 1; i++) {
      let item = htmlUtils.get(this.className_ + '-li' + i + '-inner')
      if (item) {
        item.style.marginRight = '0px'
        item.style.zIndex = ''
        item.style.right = (length - 1 - i) * (10 + this.options['itemWidth']) + 'px'
      }
    }
    this.innerElement_.style.width = this.options['itemWidth'] * length + 10 * (length - 1) + 'px'
  }
}

/**
 * 鼠标移出
 * @param event
 * @private
 */
ol.control.LayerSwitcher.prototype.contentMouseOut_ = function (event) {
  let length = this.options['layers'].length
  if (length > 0) {
    for (let i = 0; i &lt; length - 1; i++) {
      let item = htmlUtils.get(this.className_ + '-li' + i + '-inner')
      if (item) {
        item.style.zIndex = i + 1
        item.style.right = '0px'
        item.style.marginRight = (length - 1 - i) * 10 + 'px'
      }
    }
    this.innerElement_.style.width = this.options['itemWidth'] + (length - 1) * 10 + 'px'
  }
}

/**
 * 处理点击切换事件
 * @param event
 * @private
 */
ol.control.LayerSwitcher.prototype.handleClick_ = function (event) {
  let value = event.target.getAttribute('data-name')
  this.switcher(this.options['key'], value)
}

/**
 * 更新底图和标准层
 * @private
 */
ol.control.LayerSwitcher.prototype.updateBaseLayer_ = function () {
  if (!this.map) return
  this.baseLayers_ = this.getLayersArrayByKeyValue(this.baseLayerKey, true)
  this.labelLayers_ = this.getLayersArrayByKeyValue(this.labelLayerKey, true)
  if (this.baseLayers_ &amp;&amp; this.baseLayers_.length > 0) {
    this.baseLayers_.filter(_item => {
      return !!_item
    })
  }
  if (this.labelLayers_ &amp;&amp; this.labelLayers_.length > 0) {
    this.labelLayers_.filter(_item => {
      return !!_item
    })
  }
}

/**
 * 切换底图
 * @param key
 * @param value
 */
ol.control.LayerSwitcher.prototype.switcher = function (key, value) {
  if (this.forcedUpdate) {
    this.updateBaseLayer_()
  }
  console.log( key)
  console.log( this.baseLayers_)
  if (this.baseLayers_.length > 0 &amp;&amp; this.baseLayers_.length === this.options['layers'].length) {

    this.baseLayers_.forEach(layer => {
      if (layer &amp;&amp; layer.get(key) === value) {
        layer.setVisible(true)
        layer.set(this.isDefaultKey, true)
      } else {
        layer.setVisible(false)
        layer.set(this.isDefaultKey, false)
      }
    })
    let length = this.options['layers'].length
    if (length > 0) {
      for (let i = 0; i &lt; length; i++) {
        let item = htmlUtils.get(this.className_ + '-li' + i + '-inner')
        if (item &amp;&amp; item.getAttribute('data-name') === value) {
          htmlUtils.addClass(item, 'selected-item')
        } else {
          htmlUtils.removeClass(item, 'selected-item')
        }
      }
    }
  } else {
    throw new Error('请检查是否存在底图获取底图数量是否和配置相同！')
  }
}

/**
 * setMap
 * @param map
 */
ol.control.LayerSwitcher.prototype.setMap = function (map) {
  ol.control.Control.prototype.setMap.call(this, map)
  this.map = map
  if (map &amp;&amp; map instanceof ol.Map) {
    this.updateBaseLayer_()
  }
}

let olControlLayerSwitcher = ol.control.LayerSwitcher
export default olControlLayerSwitcher
</pre>
    </article>
</section>





		</div>
	</div>

	<div class="clearfix"></div>

	

</div>
</div>


    <div class="modal fade" id="searchResults">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">Search results</h4>
          </div>
          <div class="modal-body"></div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div>


<footer>


	<span class="copyright">
	https://lzw.me.
	</span>

<span class="jsdoc-message">
	Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a>
	
		on Sun Aug 12th 2018
	
	using the <a href="https://github.com/docstrap/docstrap">DocStrap template</a>.
</span>
</footer>

<script src="scripts/docstrap.lib.js"></script>
<script src="scripts/toc.js"></script>

    <script type="text/javascript" src="scripts/fulltext-search-ui.js"></script>


<script>
$( function () {
	$( "[id*='$']" ).each( function () {
		var $this = $( this );

		$this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) );
	} );

	$( ".tutorial-section pre, .readme-section pre, pre.prettyprint.source" ).each( function () {
		var $this = $( this );

		var example = $this.find( "code" );
		exampleText = example.html();
		var lang = /{@lang (.*?)}/.exec( exampleText );
		if ( lang && lang[1] ) {
			exampleText = exampleText.replace( lang[0], "" );
			example.html( exampleText );
			lang = lang[1];
		} else {
			var langClassMatch = example.parent()[0].className.match(/lang\-(\S+)/);
			lang = langClassMatch ? langClassMatch[1] : "javascript";
		}

		if ( lang ) {

			$this
			.addClass( "sunlight-highlight-" + lang )
			.addClass( "linenums" )
			.html( example.html() );

		}
	} );

	Sunlight.highlightAll( {
		lineNumbers : true,
		showMenu : true,
		enableDoclinks : true
	} );

	$.catchAnchorLinks( {
        navbarOffset: 10
	} );
	$( "#toc" ).toc( {
		anchorName  : function ( i, heading, prefix ) {
			return $( heading ).attr( "id" ) || ( prefix + i );
		},
		selectors   : "#toc-content h1,#toc-content h2,#toc-content h3,#toc-content h4",
		showAndHide : false,
		smoothScrolling: true
	} );

	$( "#main span[id^='toc']" ).addClass( "toc-shim" );
	$( '.dropdown-toggle' ).dropdown();

    $( "table" ).each( function () {
      var $this = $( this );
      $this.addClass('table');
    } );

} );
</script>



<!--Navigation and Symbol Display-->


<!--Google Analytics-->



    <script type="text/javascript">
        $(document).ready(function() {
            SearcherDisplay.init();
        });
    </script>


</body>
</html>
